<?php
namespace app\api\controller;

use app\common\controller\ApiBase;
use app\common\model\Company;
use app\common\model\KfUser;
use app\common\model\KfSession;
use app\common\model\KfSessionMessage;
use think\facade\Config;
use think\facade\Log;

class Kf extends ApiBase
{
    /**
     * @var array 除login接口外其他接口都需要checkLogin
     */
    protected $beforeActionList = [
        'checkLogin' =>  ['only'=>'getSessionList,changeKf,getSessionMessageList,getSessionNewMessage,sendSessionMessage'],
    ];

    protected $template=['7'=>'aZsI2ZPvLQ-3XmdOiEQ9h7anCp3OCkYPdhbB-jdx2iw','8'=>'ozD4nalK8gb3QT_4nltVhY-KRVBdnK-nOPryPH6UWzo'];

    public function initialize()
    {
        parent::initialize();
    }
    /**
     * 检查用户是否登录
     */
    protected function checkLogin(){
        $openid=session('kf.openid');
        if (empty($openid)) $this->ajaxReturn(false, 'please login');
        return true;
    }
    public function index(){
        $host = get_full_host();
        if (!isset($this->get['cpm']) ||  empty($this->get['cpm'])){
            $this->ajaxReturn(false, '授权失败，公司信息错误');
        }
        $cpm = $this->get['cpm'];
        ///默认跳主页
        $index = $host . '/shop/#/index?cpm=' . $cpm;
        session('referer', $index);

        $redirect_url = $host . '/api/kf/jump?cpm=' . $cpm;
        $redirect_url = urlencode($redirect_url);
        $oauth_url = $host . '/weixin/weiXin/wxOauthUser?company='.$cpm.'&redirect='.$redirect_url;
        header("Location:".$oauth_url);
    }
    public function jump(){
        $wx_user = session('wx_user');
        $cpm = $this->get['cpm'];
        $referer =  session('referer');
        //客服登录信息
        $kf = KfUser::where('openid', $wx_user['openid'])->where('cpm',$cpm)->where('status',1)->find();
        if(!empty($kf)){
            $referer=get_full_host().'/chat/#/service/index';
        }
        session('kf', $kf);       
        echo "<script>location.href='".$referer."'</script>";
    }
    /**
     * 返回客服分组列表
     */
    public function group()
    {
        $group=\Wechat::$customer_group;
        $this->ajaxReturn($group);
    }
    /**
     * 获取客服信息
     */
    public function kfInfo()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        $kf=KfUser::where('openid',$openid)->where('cpm',$cpm)->where('status',1)->find();
        if(empty($kf)){
            $this->ajaxReturn(false,'不存在该客服');
        }
        $this->ajaxReturn($kf);
    }
    /**
     * 获取所有客服 或者分组客服 或者online客服
     */
    public function kfList()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        $where=[];
        if(isset($this->get['group'])&& !empty($this->get['group'])){
            $where['group']=$this->get['group'];
        }
        if(isset($this->get['online'])&&!empty($this->get['online'])){
            $where['expire_time']=['>',time()];
        }
        //是否除开自己
        $where_ex='';
        if(true){
            $where_ex="openid <> '".$openid."'";
        }
        $kf=KfUser::where('cpm',$cpm)->where($where)->where($where_ex)->where('status',1)->order('expire_time desc')->select();
        $result=[];
        if(!$kf->isEmpty()){
            $result=$kf->toArray();
            $group=\Wechat::$customer_group;
            $group=array_combine(array_column($group,'str'),$group);
            foreach ($result as $key => $value) {
                $result[$key]['is_online']=$value['expire_time']>time() ? 1:0;
                $group_name=[];
                if(!empty($value['group'])){
                    $str=explode(',', $value['group']);
                    foreach ($str as $key => $v) {
                        if(array_key_exists($v,$group)) $group_name[]=$group[$v]['content'];
                    }
                }
                $result[$key]['group_name']=implode(',',$group_name);
            }
        }
        $this->ajaxReturn($result);
    }
    /**
     * 定时任务 有未回复客服消息 通知客服消息
     */
    public function newMessageNotice()
    {
        KfSessionMessage::where('is_see',0)->where('is_delete',0)->where('is_send',0)->field('distinct session_id')->select()->each(function ($val){
            $kf_session=KfSession::where('id',$val['session_id'])->find();
            $kf_session_message=[];
            if(!empty($kf_session)){
                $kf_openid='';
                $kf_session_message=KfSessionMessage::where('session_id',$kf_session['id'])->where('is_delete',0)->field('msg_type,content,time')->order('time desc')->find();
                if(!empty($kf_session['kf_openid'])){//会话未超时 客服就下线了
                    $kf_openid=$kf_session['kf_openid'];
                }else{//临时会话 
                    //随机一个客服或者之前有过会话的客服 接入然后通知
                    $kf_session_old=KfSession::where('user_openid',$kf_session['user_openid'])->where("kf_openid <>'' ")->where('cpm',$kf_session['cpm'])->order('expire_time desc')->find();
                    $kf_array=[];
                    if(!empty($kf_session_old)) $kf_array=KfUser::where('status',1)->where('cpm',$kf_session['cpm'])->where('openid',$kf_session_old['kf_openid'])->find();
                    if(empty($kf_session_old) || empty($kf_array)){
                        $kf=KfUser::where('status',1)->where('cpm',$kf_session['cpm'])->select();
                        if(!$kf->isEmpty()){
                            $kf=$kf->toArray();
                            //随机一个客服 接入
                            $kf_array=$kf[mt_rand(0,count($kf)-1)];
                            if(!empty($kf_array)){
                                $kf_openid=$kf_array['openid'];
                            }
                        }
                    }else{
                        $kf_openid=$kf_session_old['kf_openid'];
                    }
                    if(!empty($kf_openid)){
                        //查询这个用户和客服有没有历史会话
                        $history_session=KfSession::where('user_openid',$kf_session['user_openid'])->where('kf_openid',$kf_openid)->where('cpm',$kf_session['cpm'])->find();
                        if(!empty($history_session)){
                            KfSession::where('id',$history_session['id'])->update(['is_delete'=>0,'expire_time'=>time()+1800]);
                            $new_kf_session_id=$history_session['id'];
                            //删除临时会话
                            KfSession::where('id',$kf_session['id'])->delete();
                        }else{//没有 把这个临时会话绑给客服
                            KfSession::where('id',$kf_session['id'])->update(['kf_openid'=>$kf_openid,'expire_time'=>time()+1800,'time'=>time()]);
                            $new_kf_session_id=$kf_session['id'];
                        }
                        //把会话消息 绑给接入客服
                        KfSessionMessage::where('from',$kf_session['user_openid'])->where('session_id',$kf_session['id'])->update(['session_id'=>$new_kf_session_id,'to'=>$kf_openid]);
                    }
                }    
                if(!empty($kf_openid)){
                    $this->setCpmConfig($kf_session['cpm']);
                    $user_info=\Wechat::getUserInfo($kf_session['user_openid']);
                    $uname=empty($user_info)? '':$user_info['nickname'];

                    $href=Config::get('config.wx_host').'api/kf/index?cpm='.$kf_session['cpm'];
                    // $content = sprintf("你有新的客服消息,请注意查看回复\n\n<a href='%s'>快速查看</a>", $href);
                    // \Wechat::sendCustomerMsg($kf_openid,'text',$content);
                    $template=$this->template;
                    $data=[];
                    $data['company']=$kf_session['cpm'];
                    $data['openid']=$kf_openid;
                    $data['template_id']=$template[$kf_session['cpm']];
                    $data['url']=$href;
                    $data['content']='你有新的消息';
                    $data['keyword1']=$uname;
                    $data['keyword2']=empty($kf_session_message) ? date('Y年m月d日 H:i:s') : date('Y年m月d日 H:i:s',$kf_session_message['time']);
                    $data['keyword3']=empty($kf_session_message) ? '点击查看' :$this->returnMsgTip($kf_session_message['msg_type'],json_decode($kf_session_message['content'],true));
                    $data['remark']='你有新的用户咨询消息,请注意查看并回复。';
                    controller('\app\weixin\controller\WeiXin')->sendArticleAction($data);
                    KfSessionMessage::where('session_id',$kf_session['id'])->where('is_send',0)->update(['is_send'=>1,'send_time'=>time()]);
                }
            }
        });
    }
    /**
     * 定时任务  检测会话过期删除 
     */
    public function cleanSession()
    {
        //过期的
        KfSession::where('expire_time < '.time())->where('is_delete',0)->where("kf_openid <> ''")->field('id,cpm,user_openid')->select()->each(function ($val){
            //删除会话消息
            KfSessionMessage::where('session_id',$val['id'])->update(['is_delete'=>1]);
            //删除会话
            KfSession::where('id',$val['id'])->update(['is_delete'=>1]);
            //发送评价菜单
            $this->setCpmConfig($val['cpm']);
            $this->sendCommentMenu($val['user_openid']);
            $cache_key='comment_'.$val['user_openid'].'_'.$val['cpm'];
            cache($cache_key,['session_id'=>$val['id']],1800);
        });
    }
    /**
     * 获取客服的会话列表 并返回是否有为阅读信息
     */
    public function getSessionList()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        // if (!isset($this->get['cpm'])) {
        //     $this->ajaxReturn(false,'error cpm');
        // }
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        //请求了这里标记客服在线
        $this->setKfOnline($cpm,$openid);
        //未过期
        $this->setCpmConfig($cpm);
        $kf_session=KfSession::where(['cpm'=>$cpm,'kf_openid'=>$openid])->where('expire_time >'.time())->where('is_delete',0)->select()->each(function ($val){
            $kf_session_message=KfSessionMessage::where('session_id',$val['id'])->where('is_delete',0)->field('msg_type,content,time')->order('time desc')->find();
            $kf_session_message_nosee=KfSessionMessage::where('session_id',$val['id'])->where('is_delete',0)->where('is_see',0)->count();
            $user_info=\Wechat::getUserInfo($val['user_openid']);
            $val['uname']=empty($user_info)? '':$user_info['nickname'];
            $val['headimgurl']=empty($user_info)? '':$user_info['headimgurl'];
            $val['msg_type']='';
            $val['msg_time']=$val['time'];
            $val['content']='';
            $val['nosee_count']=$kf_session_message_nosee>0? $kf_session_message_nosee :0;
            if(!empty($kf_session_message)){
                $val['msg_type']=$kf_session_message['msg_type'];
                $val['msg_time']=date('Y-m-d H:i:s',$kf_session_message['time']);
                $val['content']=$this->returnMsgTip($kf_session_message['msg_type'],json_decode($kf_session_message['content'],true));
            }
        });
        if(!$kf_session->isEmpty()){
            $kf_session = $kf_session->toArray();
            
            array_multisort(array_column($kf_session,'msg_time'),SORT_DESC,$kf_session);
        }
        $this->ajaxReturn($kf_session);
    }
    private function returnMsgTip($type,$message)
    {
        $tip='';
        switch ($type) {
            case 'text':
                $tip=$message['Content'];
                break;
            case 'image'://图片
                $tip='[图片]';
                break;
            case 'voice'://语音
                $tip='[语音]';
                break;
            case 'shortvideo':
            case 'video'://视频
                $tip='[视频]';
                break;
            case 'location':
                $tip='[地理位置]';
                break;
            case 'link'://
                $tip='[链接]';
                break;
        }
        return $tip;
    }
    /**
     * 获取未接入的会话
     */
    public function getUnAccessSessionList()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        // if (!isset($this->get['cpm'])) {
        //     $this->ajaxReturn(false,'error cpm');
        // }
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        //请求了这里标记客服在线
        $this->setKfOnline($cpm,$openid);
        $this->setCpmConfig($cpm);
        //未接入
        $kf_session=KfSession::where(['cpm'=>$cpm,'kf_openid'=>''])->where('is_delete',0)->select()->each(function ($val){
            $kf_session_message=KfSessionMessage::where('session_id',$val['id'])->where('is_delete',0)->field('msg_type,content,time')->order('time desc')->find();
            $kf_session_message_nosee=KfSessionMessage::where('session_id',$val['id'])->where('is_delete',0)->where('is_see',0)->count();

            $user_info=\Wechat::getUserInfo($val['user_openid']);
            $val['uname']=empty($user_info)? '':$user_info['nickname'];
            $val['headimgurl']=empty($user_info)? '':$user_info['headimgurl'];
            $val['msg_type']='';
            $val['msg_time']=$val['time'];
            $val['content']='';
            $val['nosee_count']=$kf_session_message_nosee>0? $kf_session_message_nosee :0;
            if(!empty($kf_session_message)){
                $val['msg_type']=$kf_session_message['msg_type'];
                $val['msg_time']=$kf_session_message['time'];
                $val['content']=$kf_session_message['msg_type']=='text' ? json_decode($kf_session_message['content'],true)['Content'] : '';
            }
        });
        if(!$kf_session->isEmpty()){
            $kf_session = $kf_session->toArray();
            
            array_multisort(array_column($kf_session,'msg_time'),SORT_DESC,$kf_session);
        }
        $this->ajaxReturn($kf_session);
    }
    /**
     * 接入客服
     */
    public function accessKf()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        // if (!isset($this->get['cpm'])) {
        //     $this->ajaxReturn(false,'error cpm');
        // }
        if(!isset($this->get['kf_session_id']) || empty($this->get['kf_session_id'])){
            $this->ajaxReturn(false,'error kf_session_id');
        }
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        $kf_session=KfSession::where('id',$this->get['kf_session_id'])->find();
        if(empty($kf_session)){
            $this->ajaxReturn(false,'不存在消息');
        }
        if(!empty($kf_session['kf_openid'])){
            $this->ajaxReturn(false,'其他客服已经接入');
        }
        //查询这个用户和客服有没有历史会话
        $history_session=KfSession::where('user_openid',$kf_session['user_openid'])->where('kf_openid',$openid)->where('cpm',$cpm)->find();
        if(!empty($history_session)){
            KfSession::where('id',$history_session['id'])->update(['is_delete'=>0,'expire_time'=>time()+1800]);
            $new_kf_session_id=$history_session['id'];
            //删除临时会话
            KfSession::where('id',$kf_session['id'])->delete();
        }else{//没有 把这个临时会话绑给客服
            KfSession::where('id',$kf_session['id'])->update(['kf_openid'=>$openid,'expire_time'=>time()+1800,'time'=>time()]);
            $new_kf_session_id=$kf_session['id'];
        }
        //把会话消息 绑给接入客服
        KfSessionMessage::where('from',$kf_session['user_openid'])->where('session_id',$kf_session['id'])->update(['session_id'=>$new_kf_session_id,'to'=>$openid]);
        $this->ajaxReturn('ok');
    }
    /**
     * 转接客服
     */
    public function changeKf()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        // if (!isset($this->get['cpm'])) {
        //     $this->ajaxReturn(false,'error cpm');
        // }
        if(!isset($this->get['kf_session_id'])){
            $this->ajaxReturn(false,'error message_id');
        }
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        if(!isset($this->get['new_openid'])|| empty($this->get['new_openid'])){
            $this->ajaxReturn(false,'error new_openid');
        }
        $kf_user_new=KfUser::where('openid',$this->get['new_openid'])->where('cpm',$cpm)->where('status',1)->find();
        if(empty($kf_user_new)){
            $this->ajaxReturn(false,'客服不存在');
        }
        $kf_session=KfSession::where('id',$this->get['kf_session_id'])->find();
        if(empty($kf_session) || $kf_session['kf_openid']!=$openid){
            $this->ajaxReturn(false,'不存在或无效会话');
        }
        if($kf_session['kf_openid']==$this->get['new_openid']){
            $this->ajaxReturn(false,'和原来客服相同');
        }
        //查询这个用户和新客服有没有历史会话
        $history_session=KfSession::where('user_openid',$kf_session['user_openid'])->where('kf_openid',$this->get['new_openid'])->where('cpm',$cpm)->find();
        if(!empty($history_session)){
            $new_session_id=$history_session['id'];
            KfSession::where('id',$history_session['id'])->update(['is_delete'=>0,'expire_time'=>time()+1800]);
        }else{
            $new_session_id=KfSession::insertGetId(['cpm'=>$cpm,'kf_openid'=>$this->get['new_openid'],'user_openid'=>$kf_session['user_openid'],'expire_time'=>time()+1800,'time'=>time()]);
        }
        //同步消息
        $this->syncSesssionMessage($kf_session,$new_session_id);
        //通知新客服
        $this->newMessageNotice();
        //删除会话消息
        KfSessionMessage::where('session_id',$kf_session['id'])->update(['is_delete'=>1]);
        //删除会话
        KfSession::where('id',$kf_session['id'])->update(['is_delete'=>1]);
        $this->ajaxReturn('ok');
    }
    /**
     * 转接客服 同步用户的聊天记录
     */
    private function syncSesssionMessage($session,$new_session_id)
    {
        //用户发的消息
        $message= KfSessionMessage::where('session_id',$session['id'])->where('from',$session['user_openid'])->where('is_delete',0)->order('id asc')->select();
        $new_session=KfSession::where('id',$new_session_id)->find();
        if(!$message->isEmpty()){
            $message=$message->toArray();
            $all_data=[];
            $data=['cpm'=>$session['cpm'],'session_id'=>$new_session_id];
            foreach ($message as $key => $value) {
                $data['from']=$new_session['user_openid'];
                $data['to']=$new_session['kf_openid'];
                $data['msg_type']=$value['msg_type'];
                $data['content']=$value['content'];
                $data['time']=$value['time'];
                $all_data[]=$data;
            }
            if(!empty($all_data)) KfSessionMessage::insertAll($all_data);
        }
    }
    /**
     * 获取和某一个用户会话 历史内容
     */
    public function getSessionMessageList()
    {
        if(!isset($this->get['kf_session_id']) || empty($this->get['kf_session_id'])){
            $this->ajaxReturn(false,'error kf_session_id');
        }
        $openid=session('kf.openid');
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        $kf_session=KfSession::where('id',$this->get['kf_session_id'])->where('is_delete',0)->find();
        if(empty($kf_session) || $kf_session['kf_openid']!=$openid){
            $this->ajaxReturn(false,'不存在或者无效会话');
        }
        $page=0;
        if(isset($this->get['page'])){
            $page=(int)$this->get['page'];
        }
        
        //直接标记这个会话的未读消息 为已读
        KfSessionMessage::where('session_id',$kf_session['id'])->where('is_see',0)->update(['is_see'=>1,'see_time'=>time()]);
        
        $kf_session_message=KfSessionMessage::where('session_id',$this->get['kf_session_id'])->where('is_delete',0)->where('is_see',1)->order('time desc')->page($page, 20)->select()->each(function($val) use($openid){
            if($val['from']==$openid){
                $kf=KfUser::where('cpm',$val['cpm'])->where('openid',$openid)->find();
                $val['uname']=empty($kf)? '' :$kf['uname'];
                $val['headimgurl']=empty($kf)? '' :$kf['headimgurl'];
            }else{
                $this->setCpmConfig(session('kf.cpm'));
                $user_info=\Wechat::getUserInfo($val['from']);
                $val['uname']=empty($user_info)? '':$user_info['nickname'];
                $val['headimgurl']=empty($user_info)? '':$user_info['headimgurl'];
            }
            $val['content']=json_decode($val['content'],true);
            $val['time']=date('Y-m-d H:i:s',$val['time']);
            $val['is_self']=$val['from']==$openid ? 1:0;
        });
        $result=[];
        if(!$kf_session_message->isEmpty()){
            $result=$kf_session_message->toArray();
            // $result=array_reverse($result);
        }
        $this->ajaxReturn($result);
    }
    /**
     * 获取最新消息 未读
     */
    public function getSessionNewMessage()
    {
        if(!isset($this->get['kf_session_id'])){
            $this->ajaxReturn(false,'error kf_session_id');
        }
        $openid=session('kf.openid');
        session_commit();
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        $kf_session=KfSession::where('id',$this->get['kf_session_id'])->where('is_delete',0)->find();
        if(empty($kf_session) || $kf_session['kf_openid']!=$openid){
            $this->ajaxReturn(false,'不存在或者无效会话');
        }
              
        //前端呈现了  回传标记已读
        if(isset($this->get['send_data']) && !empty($this->get['send_data'])){
            
            KfSessionMessage::where('id in ( '.$this->get['send_data'].' ) ')->update(['is_see'=>1,'see_time'=>time()]);
        }
        //请求了这里标记客服在线
        $this->setKfOnline($kf_session['cpm'],$openid);
        //直接标记这个会话的未读消息 为已读
        KfSessionMessage::where('session_id',$kf_session['id'])->where('is_see',0)->update(['is_see'=>1,'see_time'=>time()]);

        set_time_limit(0);//无限请求超时时间      
        $i=0;    
        $time=30;  
        while (true){         
            $i++;      
            //若得到数据则马上返回数据给客服端，并结束本次请求         
            $kf_session_message=KfSessionMessage::where('session_id',$this->get['kf_session_id'])->where('is_delete',0)->where('is_see',0)->order('time asc')->select()->each(function($val) use ($openid){
                if($val['from']==$openid){
                    $kf=KfUser::where('cpm',$val['cpm'])->where('openid',$openid)->find();
                    $val['uname']=empty($kf)? '' :$kf['uname'];
                    $val['headimgurl']=empty($kf)? '' :$kf['headimgurl'];
                }else{
                    $this->setCpmConfig(session('kf.cpm'));
                    $user_info=\Wechat::getUserInfo($val['from']);
                    $val['uname']=empty($user_info)? '':$user_info['nickname'];
                    $val['headimgurl']=empty($user_info)? '':$user_info['headimgurl'];
                }
                $val['content']=json_decode($val['content'],true);
                $val['time']=date('Y-m-d H:i:s',$val['time']);
                $val['is_self']=$val['from']==$openid ? 1:0;
                
            }); 
            $result=[];
            if(!$kf_session_message->isEmpty()){
                $result=$kf_session_message->toArray();
                $this->ajaxReturn($result);
            }     
            //服务器($_POST['time']*0.5)秒后告诉客服端无数据      
            if($i==$time){      
                $this->ajaxReturn('ok');      
            } 
            sleep(1);     
        }
    }
    /**
     * 客服发送消息
     */
    public function sendSessionMessage()
    {
        $cpm=session('kf.cpm');
        $openid=session('kf.openid');
        // if (!isset($this->get['cpm'])) {
        //     $this->ajaxReturn(false,'error cpm');
        // }
        if(!isset($this->get['kf_session_id']) || empty($this->get['kf_session_id'])){
            $this->ajaxReturn(false,'err kf_session_id');
        }
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        if(!isset($this->get['msg_type']) || !in_array($this->get['msg_type'],['text','image','video'])){
            $this->ajaxReturn(false,'暂不支持此类型消息');
        }
        $kf_session=KfSession::where('id',$this->get['kf_session_id'])->find();
        if(empty($kf_session) || $kf_session['kf_openid']!=$openid){
            $this->ajaxReturn(false,'不存在该会话');
        }
        if($kf_session['expire_time']<time()){
            //删除会话消息
            KfSessionMessage::where('session_id',$kf_session['id'])->update(['is_delete'=>1]);
            //删除会话
            KfSession::where('id',$kf_session['id'])->update(['is_delete'=>1]);
            $this->ajaxReturn(false,'会话已超时');
        }
        $content=[];
        $message_content=[];
        $this->setCpmConfig((int)$cpm);
        switch ($this->get['msg_type']) {
            case 'text':
                if(!isset($this->get['content']) || empty($this->get['content'])){
                    $this->ajaxReturn(false,'内容为空');
                }
                $content=$this->get['content'];
                $message_content['Content']=$content;
                break;
            case 'image':
                if(!isset($this->get['content']) || empty($this->get['content'])){
                    $this->ajaxReturn(false,'内容为空');
                }
                if(!$media_id=\Wechat::upload('image',ROOT_PATH.'/'.$this->get['content'])){
                        $this->ajaxReturn(false,'请再试一次');
                }
                $content['media_id']=$media_id;
                $message_content=$content;
                $message_content['image_url']=$this->get['content'];
                break;
            case 'video':
                if(!isset($this->get['content']) || empty($this->get['content'])){
                    $this->ajaxReturn(false,'内容为空');
                }
                if(!$media_id=\Wechat::upload('video',ROOT_PATH.$this->get['content'])){
                    $this->ajaxReturn(false,'请再试一次');
                }
                $content['media_id']=$media_id;
                $content['thumb_media_id']='';
                $content['title']='';
                $content['description']='';
                $message_content=$content;
                $message_content['video_url']=$this->get['content'];
                break;
        }
        $this->setCpmConfig((int)$cpm);
        if(\Wechat::sendCustomerMsg($kf_session['user_openid'],$this->get['msg_type'],$content)){
            //记录客服消息
            KfSessionMessage::create(['cpm'=>$kf_session['cpm'],'session_id'=>$kf_session['id'],'from'=>$kf_session['kf_openid'],'to'=>$kf_session['user_openid'],'msg_type'=>$this->get['msg_type'],'content'=>json_encode($message_content),'is_see'=>1,'see_time'=>time(),'time'=>time()]);
            //更新会话过期时间
            KfSession::where('id',$kf_session['id'])->update(['expire_time'=>time()+1800]);
            $this->ajaxReturn(true,'发送成功');
        }else{
            $this->ajaxReturn(false,'请再试一次');
        }
    }
    /**
     * image  * 文件名
     * folder * 上传目录
     * thumb  * 是否生成缩略图
     */
    public function uploadImage(){

        $file = $this->param['image'];
        if($file){
            $path = './static/upload/wxkf';
            $new_file = $path."/".date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)){
                $type = $result[2];
                $new_file = $new_file.time().".".$type;
                $file= str_replace(' ', '+', $file);
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $file)))){
                    $this->ajaxReturn($new_file);
                }else{
                    return $this->ajaxReturn(false,'保存失败');
                }
            }else{
                $this->ajaxReturn(false,'base64');
            }

        }else{
            $this->ajaxReturn(false,'请选择上传文件');
        }
    }
    private function base64_image_content($base64_image_content,$path){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = $path."/".date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return '/'.$new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     * 客服主动关闭会话
     */
    public function closeSession()
    {
        if(!isset($this->get['kf_session_id'])){
            $this->ajaxReturn(false,'error kf_session_id');
        }
        $openid=session('kf.openid');
        // if(!isset($this->get['openid'])|| empty($this->get['openid'])){
        //     $this->ajaxReturn(false,'error openid');
        // }
        $kf_session=KfSession::where('id',$this->get['kf_session_id'])->find();
        if(empty($kf_session) || $kf_session['kf_openid']!=$openid){
            $this->ajaxReturn(false,'不存在或者无效会话');
        }
        //删除会话消息
        KfSessionMessage::where('session_id',$kf_session['id'])->update(['is_delete'=>1]);
        //删除会话
        KfSession::where('id',$kf_session['id'])->update(['is_delete'=>1]);
        //发送评价菜单
        $this->setCpmConfig($kf_session['cpm']);
        $this->sendCommentMenu($kf_session['user_openid']);
    }
    /**
     * 标记客服在线
     */
    private function setKfOnline($cpm,$openid)
    {
        KfUser::where('openid',$openid)->where('cpm',$cpm)->update(['expire_time'=>time()+300]);
    }
    /**
     * 发送评价菜单消息
     */
    private function sendCommentMenu($openid){
        $toUser = $openid;
        $msgType = 'msgmenu';
        $content=[];
        $content['head_content']='您对本次服务是否满意呢？';
        $content['list']=[
                            ['id'=>'90090','content'=>'1、满意'],
                            ['id'=>'90091','content'=>'2、不满意']
                        ];
        $content['tail_content']='';
        \Wechat::sendCustomerMsg($toUser,$msgType,$content);
    }
    /**
     * 公众号配置
     */
    private function setCpmConfig($cpm)
    {
        $company = Company::where('id', $cpm)->find();
        $token_arr = ['1' => 'ozvGRrYJ7555LJczRdckc7k75lZ57k2r', '2' => 'oO6bEV2oE40Z967226oeZ6EV065045iY', '3' => '', '4' => 'u9slLAJzoS00SJZjJP6SXS8LsjlxghsS', '5' => '', '6' => 'gterac3uzbb3u5fni30jc1owyg55euuj', '7' => 'xdnice2003abc', '8'=>'xdnice2019abc'];
        $appid = $company['wx_appid'];
        $appsecret = $company['wx_secret'];
        $token = $token_arr[$cpm];
        \Wechat::setConfig($appid, $appsecret, $token, $cpm);
        return true;
    }
}
